package pers.zw.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;

/**
 * form.jsp，提交表单交给Servlet处理
 */
@WebServlet(name = "ServletRequestDemo3", urlPatterns = "/ServletRequestDemo3")
public class ServletRequestDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        /*
         * 编号(文本框)
         * <input type="text" name="userid" value="NO." size="2" maxlength="2">
         */
        String userid = request.getParameter("userid");
        /*
        用户名（文本框）：<input type = "text" name = "username" value = "请输入用户名“>
         */
        String username = request.getParameter("username");

        String userpass = request.getParameter("userpass");

        String sex = request.getParameter("sex");
        String dept = request.getParameter("dept");

        String[] insts = request.getParameterValues("inst");
        String note = request.getParameter("note");
        String hiddenField = request.getParameter("hiddenField");

        StringBuilder instStr = new StringBuilder();

        for (int i = 0; insts != null && i < insts.length; i++) {
            if (i == insts.length - 1) {
                instStr.append(insts[i]);
            } else {
                instStr.append(insts[i]).append(", ");
            }
        }

        String htmlStr = "<table>" +
                "<tr><td>填写的编号：</td><td>{0}</td></tr>" +
                "<tr><td>填写的用户名：</td><td>{1}</td></tr>" +
                "<tr><td>填写的密码：</td><td>{2}</td></tr>" +
                "<tr><td>选中的性别：</td><td>{3}</td></tr>" +
                "<tr><td>选中的部门：</td><td>{4}</td></tr>" +
                "<tr><td>选中的兴趣：</td><td>{5}</td></tr>" +
                "<tr><td>填写的说明：</td><td>{6}</td></tr>" +
                "<tr><td>隐藏域的内容：</td><td>{7}</td></tr>" +
                "</table>";
        htmlStr = MessageFormat.format(htmlStr, userid, username, userpass,
                sex, dept, instStr, note, hiddenField);

        response.setCharacterEncoding("UTF-8");//设置服务器端以UTF-8编码输出数据到客户端
        response.setContentType("text/html;charset=UTF-8");//设置客户端浏览器以UTF-8编码解析数据
        response.getWriter().write(htmlStr);//输出htmlStr里面的内容到客户端浏览器显示
    }
}
